package com.meila.cms.services.impl;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.json.JSONObject;
import org.springframework.stereotype.Service;

import com.meila.cms.dao.DictMapper;
import com.meila.cms.dao.UserMapper;
import com.meila.cms.dao.UserRoleMapper;
import com.meila.cms.entity.User;
import com.meila.cms.entity.UserRole;
import com.meila.cms.model.CommonModel;
import com.meila.cms.model.ResetPwdModel;
import com.meila.cms.model.SQLAdapterModel;
import com.meila.cms.model.UserModel;
import com.meila.cms.model.VerifyCode;
import com.meila.cms.services.ILoginService;
import com.meila.cms.util.StringUtil;
import com.meila.cms.util.cache.EhcacheUtil;
import com.meila.cms.util.cache.RedisUtil;
import com.meila.cms.util.json.JsonUtil2;
import com.meila.cms.util.json.JsonUtil3;
import com.meila.cms.web.SendsmsUtil;

@Service
public class LoginService  extends BaseService  implements ILoginService{
	
  
	@Override
	public CommonModel getVerifyCode(final HttpServletRequest request,final String phone) {
		// TODO Auto-generated method stub
		CommonModel commonModel=new CommonModel();
    	
    	int vrifyCode = (int)((Math.random()*9+1)*100000);
    	
    	VerifyCode verifyCode=null;
 
    	try {
    		String mobileJsonString=RedisUtil.getString(phone);
    		String	ipJsonString=RedisUtil.getString( getRemoteHost(request));

    		
    /*    	VerifyCode verifyCode_mobile = (VerifyCode) EhcacheUtil.get("verifyCodeCache", phone);
        	
        	VerifyCode verifyCode_ip = (VerifyCode) EhcacheUtil.get("verifyCodeCache", getRemoteHost(request));*/

        	if(mobileJsonString==null && ipJsonString==null){
 
        		verifyCode=new VerifyCode();

    	    	verifyCode.setPhone(phone);
    	    	verifyCode.setVrifyCode(vrifyCode+"");
    	    	verifyCode.setIp(getRemoteHost(request));
    	    	
    	    	String  verifyCodeJson=JsonUtil3.object2json(verifyCode);
                RedisUtil.setString(phone,120 ,verifyCodeJson);
                RedisUtil.setString(getRemoteHost(request),120,verifyCodeJson);
    	    	//EhcacheUtil.put("verifyCodeCache", phone,verifyCode);
    	    	//EhcacheUtil.put("verifyCodeCache",  getRemoteHost(request),verifyCode);
    	    	
    	     	//SendsmsUtil.Send(mobile,vrifyCode+"");
    	    	SendsmsUtil.Send(phone,"您的验证码是：" + vrifyCode + "。请不要把验证码泄露给其他人。");
    	    	System.out.println("vrifyCode====>"+vrifyCode);
//    	    	Timer timer = new Timer();
//    	        timer.schedule(new TimerTask() {
//    	              public void run() {
//    	            	  EhcacheUtil.put("verifyCodeCache", phone,null);
//    	     	    	  EhcacheUtil.put("verifyCodeCache", getRemoteHost(request),null);
//    	     	    	
//    	              }
//    	          }, 1000*120*1);// 验证码2分钟后失效
    	    	
    	        commonModel.setFlag(true);
        		commonModel.setMessage("获取验证码成功");
    	    	
        	}else{
        		commonModel.setFlag(false);
        		commonModel.setMessage("获取验证码失败:每次操作间隔不能小于2分钟");
        	}
		} catch (Exception e) {
			e.printStackTrace();
			commonModel.setFlag(false);
			commonModel.setMessage("获取验证码失败:获取时出错");
		}
 
		
    	return commonModel;
	}

	//防止通过了Apache,Squid等反向代理软件就不能获取到客户端的真实IP地址了。
	public String getRemoteHost(javax.servlet.http.HttpServletRequest request){
		String ip = request.getHeader("x-forwarded-for");
		if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
		    ip = request.getHeader("Proxy-Client-IP");
		}
		if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
		    ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
		    ip = request.getRemoteAddr();
		}
		return ip.equals("0:0:0:0:0:0:0:1")?"127.0.0.1":ip;
	}

	@Override
	public CommonModel uniqueVerify(CommonModel commonModel) {
		// TODO Auto-generated method stub
		String sql;
		commonModel.setFlag(true);
		
		try{
			if("phone".equals(commonModel.getName())){
				
				sql="select count(*) from t_user where phone='"+commonModel.getValue()+"'";
				
				if(dictMapper.selectCount(new SQLAdapterModel(sql))>0){
					commonModel.setFlag(false);
					commonModel.setMessage("该电话已经注册过了");
				}
				
			}else if("resetpwd_phoneno".equals(commonModel.getName())){
				
				sql="select count(*) from t_user where phone='"+commonModel.getValue()+"'";
				
				if(dictMapper.selectCount(new SQLAdapterModel(sql))==0){
					commonModel.setFlag(false);
					commonModel.setMessage("该电话还未注册");
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
						
		return commonModel;
	}
	
	@Override
	public CommonModel dynamiccodeVerify(String dynamiccode,String phone){
		// TODO Auto-generated method stub
		CommonModel commonModel = new CommonModel();
		commonModel.setFlag(false);
		
		if(StringUtil.isEmpty(dynamiccode)){
			commonModel.setMessage("请输入验证码");
    		return commonModel;
		}else{
			
			String verifyCodeJsonString=RedisUtil.getString(phone);
			JSONObject jsonObject=JsonUtil2.stringToJSONObject(verifyCodeJsonString);
			VerifyCode verifyCode= (VerifyCode) JsonUtil2.getBean(VerifyCode.class,jsonObject);
 
			//VerifyCode verifyCode = (VerifyCode) EhcacheUtil.get("verifyCodeCache", phone);
			
			if(verifyCode==null){
				commonModel.setMessage("验证码已经过期");
    	  		return commonModel;
			}else if(verifyCode!=null && dynamiccode.equals(verifyCode.getVrifyCode())){
				commonModel.setFlag(true);
    	  		commonModel.setMessage("验证码不正确");
    	  		return commonModel;
			}else{
				commonModel.setMessage("验证码不正确");
    	  		return commonModel;
			}
		}
		
	}
	
	@Override
	public boolean addRegister(UserModel user){
		// TODO Auto-generated method stub
		//插入注册用户
		try{
			user.setCreateTime(new Date());
			user.setUpdateTime(new Date());
			user.setRemianSpace(800);
			user.setStatus(1);
			user.setDel(0);
			user.setAuthentication(0);
			userMapper.insert(user);
			//添加用户角色
			userRoleMapper.addUserRole(user.getType(), userMapper.selectMaxId());
		}catch(Exception e){
			return false;
		}
		return true;
	}
	
	@Override
	public CommonModel updatePass(HttpSession session,
					ResetPwdModel resetPwdModel) {
			// TODO Auto-generated method stub
			CommonModel commonModel=new CommonModel();
			commonModel.setFlag(true);
			commonModel.setMessage("修改密码成功");
			
			//VerifyCode verifyCode = (VerifyCode) EhcacheUtil.get("verifyCodeCache", resetPwdModel.getPhone());
			
			
			String verifyCodeJsonString=RedisUtil.getString(resetPwdModel.getPhone());
			JSONObject jsonObject=JsonUtil2.stringToJSONObject(verifyCodeJsonString);
			VerifyCode verifyCode= (VerifyCode) JsonUtil2.getBean(VerifyCode.class,jsonObject);
			
			
			if(verifyCode==null){
				commonModel.setFlag(false);
				commonModel.setMessage("修改密码失败:验证码已经失效");
			}
			try{
				if(resetPwdModel.getPhone().equals(verifyCode.getPhone())){
					
					UserModel user=userMapper.selectByPhone(resetPwdModel.getPhone());
					
					if(resetPwdModel.getPassword().equals(user.getPassword())){
						
						commonModel.setFlag(false);
						commonModel.setMessage("修改密码失败:新密码不能和原来的一样");
					}else{
						user.setUpdateTime(new Date());
						user.setPassword(resetPwdModel.getPassword());
						userMapper.updateByPrimaryKeySelective(user);
					}
				}else{
					commonModel.setFlag(false);
					commonModel.setMessage("修改密码失败");
				}
			}catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
				
				commonModel.setFlag(false);
				commonModel.setMessage("修改密码失败");
			}
			return commonModel;
	}
 
}